#include "ClientGame.h"
#include "Utils.h"

ClientGame::ClientGame(int playerId)
{
	myPlayerId = playerId;
	allMoons = new vector<ClientMoon>;
	allPlayers = new vector<ClientPlayer>;
}

void ClientGame::update(string updateString)
{
	vector<string> results;
	Utils::SplitString(updateString, "|", results, false);
	//loop through all my entities
	for(vector<string>::iterator it = results.begin(); it != results.end(); ++it)
	{
		string currentElement = *it;
		vector<string> splitElement;
		Utils::SplitString(currentElement, ",", splitElement, false);
		vector<string>::iterator it2 = splitElement.begin();
		if(*it2 == "Moon")
		{
			//moon string:  Moon,moonId,playerId,population,missileResearchLevel,shieldResearchLevel,reproduction,production,research,
			//(no newline)  currentProductionTaskName,BuildProgress,currentResearchTaskName,ResearchProgress
			//(no newline)  readyMissilePower(0 if no missile), readyShieldPower(0 if no shield)
			//see if the moon exists, if so, update it, otherwise create it
			it2++;
			int moonId = atoi((*it2).c_str());
			bool moonFound = false;
			//look for an existing moon
			for(vector<ClientMoon>::iterator itMoons = (*allMoons).begin(); itMoons != (*allMoons).end() && moonFound == false; itMoons++)
			{
				ClientMoon currentMoon = *itMoons;
				if(currentMoon.getMoonId() == moonId)
				{
					//update the moon
					moonFound = true;
					//it2 currently at moon Id
					currentMoon.init(splitElement);
				}
			}

			if(!moonFound)
			{
				it2++;
				int moonId = atoi((*it2).c_str());
				//create a new one and insert it in the vector of moons
				ClientMoon * currentMoon = new ClientMoon(moonId, splitElement);
				//add the currentMoon to the moons vector
				(*allMoons).insert((*allMoons).end(), *currentMoon);
			}
		}
		else if (*it2 == "Player")
		{
			//see if the player exists, if so, update it, otherwise create it
			it2++;
			int playerId = atoi((*it2).c_str());
			bool playerFound = false;
			//look for an existing moon
			for(vector<ClientPlayer>::iterator itPlayers = (*allPlayers).begin(); itPlayers != (*allPlayers).end() && playerFound == false; itPlayers++)
			{
				ClientPlayer currentPlayer = *itPlayers;
				if(currentPlayer.getPlayerId() == playerId)
				{
					//update the moon
					playerFound = true;
					//it2 currently at moon Id
					currentPlayer.init(&splitElement);
				}
			}

			if(!playerFound)
			{
				it2++;
				int playerId = atoi((*it2).c_str());
				//create a new one and insert it in the vector of moons
				ClientPlayer currentPlayer = *(new ClientPlayer(playerId, &splitElement));
				//add the currentMoon to the moons vector
				(*allPlayers).insert((*allPlayers).end(), currentPlayer);
			}
		}
	}
}